/**
 * Copyright (c) 2010-2011 julewa.com.  
 * All rights reserved. 
 * 
 * @author Huang Benhua
 * @date 2011-2-20
 * 
**/
package com.julewa.loading;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.Standard;
import org.apache.struts2.dispatcher.mapper.ActionMapping;

import com.opensymphony.xwork2.ActionInvocation;


public class RESTActionMapping extends ActionMapping{
	
	private Map<String, Object> parameters = new HashMap<String, Object>(); 
	public RESTActionMapping(){} 
	void setParam(String key, Object value){
		parameters.put(key, value);
		this.setParams(parameters);
	}
   
	public String setRest(HttpServletRequest request, String restString){ 
    	request.setAttribute(RESTNameMapper.REST_STRING, restString);
		//parameters.put("$REST", restString);
    	//
    	String rest[] = restString.split("/");
    	request.setAttribute(RESTNameMapper.RESTS, rest);
    	//for(int i = 0; i < rest.length; ++ i){
    	//	parameters.put("$" + i, rest[i]);
    	//}
    	//parameters.put("$COUNT", rest.length);
    	//
    	return restString;
	}
	
	public static void initRest(ActionInvocation ai, HttpServletRequest req){
		Standard std = ai.getAction().getClass().getAnnotation(Standard.class);
		if(std == null)return;
		String rests[] = (String[])req.getAttribute(RESTNameMapper.RESTS);
		if(rests == null)return;
		String rs[] = std.rest();
		int cnt = rs.length;
		if(cnt > rests.length)cnt = rests.length;
		//
		Map<String, Object> paramsMap = ai.getInvocationContext().getParameters();
		for(int i = 0; i < cnt; ++ i){
			paramsMap.put(rs[i], rests[i]);
		}
		//
		if(!"".equals(std.restString())){
			paramsMap.put(std.restString(), req.getAttribute(RESTNameMapper.REST_STRING));
		}
		if(!"".equals(std.restArray())){
			paramsMap.put(std.restArray(), rests);
		}
		if(!"".equals(std.restCount())){
			paramsMap.put(std.restCount(), rests.length);
		}
	}

}
